package com.rabbit.config;

import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.rabbit.constant.ResultCodeEnum;
import com.rabbit.constant.SecurityConstant;
import com.rabbit.exception.BusinessException;
import com.rabbit.interceptor.DemoInterceptor;
import com.rabbit.resolver.TokenArgumentResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * <h1>拦截器相关配置</h1>
 *
 * @author zjw
 * @date 2021/6/29 15:29
 */
@Configuration
public class DefaultWebMvcConfig extends AbstractWebMvcConfig implements WebMvcConfigurer {

    @Value("${rabbit-fast.demo}")
    private Boolean demo;

    /**
     * Token参数解析
     *
     * @param argumentResolvers 解析类
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new TokenArgumentResolver());
    }

    @Override
    protected void addCustomInterceptors(InterceptorRegistry registry) {
        // Demo拦截器
        if (demo) {
            registry.addInterceptor(new DemoInterceptor());
        }
        // Sa路由拦截器
        registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
            // OPTIONS跳过
            SaRouter.match(SaHttpMethod.OPTIONS).back();
            // 登录认证 -- 排除/login相关，其他都需要登录认证
            SaRouter.match("/**").notMatch("/login", "/validate/code/*", "/druid/*").check(r -> StpUtil.checkLogin());
            // 权限认证 -- 不同模块认证不同角色
            SaRouter.match("/user/**", "/role/**", "/menu/**", "/token/**", "/config/**", "/dict/**", "/dictData/**", "/file/**",
                    "/operLog/**", "/loginLog/**").check(r -> StpUtil.checkRole(SecurityConstant.SUPER_ADMIN));
        })).addPathPatterns("/**");
    }
}
